package com.zzz.gp.task;

import com.zzz.gp.bean.MailBean;
import com.zzz.gp.bean.vo.AlarmCode;
import com.zzz.gp.config.MailConfig;
import com.zzz.gp.dao.GpMapper;
import com.zzz.gp.utils.HttpRequestUtil;
import com.zzz.gp.utils.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 * @time: 2021/12/15 16:56
 */
@Slf4j
@Component
public class GpAlarmTask {
    @Autowired
    private MailConfig mailConfig;
    @Autowired
    private MailService mailService;
    @Autowired
    private GpMapper gpMapper;

    private Map<String, Integer> map = new HashMap<>();
    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Value("${gp.alarm.enable}")
    private boolean enable;

    @Value("${gp.email.alarm.enable}")
    private boolean emailEnable;

    @Scheduled(cron = "${gp.alarm.clean.map}")
    public void cleanMap() {
        log.info("=====定时任务清理Map缓存: gp.alarm.clean.map=====");
        //清理map
        map.clear();
        //清理表alarm_code
        //gpMapper.cleanAlarmCode();
    }

    @Scheduled(cron = "${gp.alarm.cron1}")
    public void alarmCron1() {
        if (!enable) {
            return;
        }
        exeTask();
    }

    @Scheduled(cron = "${gp.alarm.cron2}")
    public void alarmCron2() {
        if (!enable) {
            return;
        }
        exeTask();
    }

    @Scheduled(cron = "${gp.alarm.cron3}")
    public void alarmCron3() {
        if (!enable) {
            return;
        }
        exeTask();
    }

    public void exeTask() {
        String today = dtf.format(LocalDate.now());
        String url = "http://hq.sinajs.cn/list=";
        List<AlarmCode> list = gpMapper.getAlarmCode();
        if (list.size() > 0) {
            list.forEach(x -> {
                String name = x.getName();
                String code = x.getCode();
                String type = x.getType();
                double rate = Double.parseDouble(x.getRate());
                int turnover = Integer.parseInt(x.getTurnover());
                //查询
                String result = HttpRequestUtil.httpRequest(url + code);
                if (result.length() > 30) {
                    String[] split = result.split(",");
                    String yesterday_price = split[2];
                    String today_price = split[3];
                    int t_turnover = Integer.parseInt(split[10]);

                    BigDecimal y_price = new BigDecimal(yesterday_price);
                    BigDecimal t_price = new BigDecimal(today_price);

                    //涨幅 小数
                    BigDecimal increase = (t_price.subtract(y_price)).divide(y_price, 4, BigDecimal.ROUND_HALF_UP);
                    //涨幅 百分比
                    String increase_p = increase.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();

                    Double p = Double.parseDouble(increase_p);
                    log.info("{} {}  {}%  BUY ONE:{}", today, code, increase_p, t_turnover);

                    //-1 rate 小于
                    //1  rate 大于
                    //0 turnover
                    if ("-1".equals(type)) {
                        if (p < rate) {
                            //告警
                            String key = type + "_" + code;
                            String subject = "GP 达到预期 PRICE !!!";
                            String content = name + "(" + code + ") " + increase_p + "%";
                            alarm(key, content, subject);
                        }
                    }
                    if ("1".equals(type)) {
                        if (p > rate) {
                            //告警
                            String key = type + "_" + code;
                            String subject = "GP 达到预期 PRICE !!!";
                            String content = name + "(" + code + ") " + increase_p + "%";
                            alarm(key, content, subject);
                        }
                    }


                    if ("0".equals(type)) {
                        if (t_turnover < turnover) {
                            String key = type + "_" + code;
                            String subject = "GP 炸板了 ！！！";
                            String content = name + "(" + code + ") " + "快炸板了";
                            alarm(key, content, subject);
                        }
                    }
                }
            });

        } else {
            map.clear();
        }
    }

    public void alarm(String key, String content, String subject) {
        //判断是否是首次告警
        if (!map.containsKey(key)) {
            map.put(key, 1);
            //发送邮件告警
            if (emailEnable) {
                sendEmail(content, subject);
            }
        } else {
            int n = map.get(key);
            if (n < 5) {
                map.put(key, n + 1);
                //发送邮件告警
                if (emailEnable) {
                    sendEmail(content, subject);
                }
            }
        }
    }


    public void sendEmail(String content, String subject) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //String nowTime = dtf.format(LocalDateTime.now());
        //String subject = "股票告警通知" + " " + nowTime;
        MailBean mailBean = new MailBean();
        mailBean.setFrom(mailConfig.getFrom());
        mailBean.setTo(mailConfig.getTo());
        mailBean.setCc(mailConfig.getCc());
        mailBean.setSubject(subject);
        mailBean.setContent(content);
        mailService.sendTextMail(mailBean);
    }
}
